package com.gxgeek.javabasic.guava;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author gaoxing
 * @create 2017-11-27 下午2:50
 */
@Slf4j
public class GuavaDemo {

//    public static void main(String[] args) throws InterruptedException {
//        RateLimiter limiter = RateLimiter.create(2.0) ;
//        //批量调用
//        for (int i = 0 ;i< 10 ; i++){
//            double acquire = limiter.acquire();
//            log.debug("获取令牌成功!,消耗=" + acquire);
//            Thread.sleep(1);
//            log.debug("远程返回:");
//        }
//
//    }
public static void main(String[] args) {
    testNoRateLimiter();
    testWithRateLimiter();
}

    public static void testNoRateLimiter() {
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 10; i++) {
            System.out.println("call execute.." + i);

        }
        Long end = System.currentTimeMillis();

        System.out.println(end - start);

    }

    public static void testWithRateLimiter() {
        Long start = System.currentTimeMillis();
        RateLimiter limiter = RateLimiter.create(10.0); // 每秒不超过10个任务被提交
        for (int i = 0; i < 100; i++) {
            limiter.acquire(); // 请求RateLimiter, 超过permits会被阻塞
            System.out.println("call execute.." + i);

        }
        Long end = System.currentTimeMillis();

        System.out.println(end - start);

    }

}
